package org.jeecg.modules.foc;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.util.Md5Util;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.common.FocRequest;
import org.jeecg.modules.common.FocRespone;
import org.jeecg.modules.foc.entity.*;
import org.jeecg.modules.foc.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Api(tags = "foc操作")
@RestController
@RequestMapping("/foc/auto")
public class FocController {

    @Value("${ems.url}")
    public String emsUrl;

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    private IFocPointDataService focPointDataService;
    @Autowired
    private IFocConfigService focConfigService;
    @Autowired
    private IFocSpaceService focSpaceService;

    @Autowired
    private IFocPointService focPointService;
    @Autowired
    private IFocDeviceService focDeviceService;
    @Autowired
    private IFocStrategyService focStrategyService;


    /**
     * 重新生成所有点位节点
     */
    @AutoLog(value = "foc操作-手动刷新-点位")
    @ApiOperation(value = "foc操作-手动刷新-点位", notes = "foc操作-手动刷新-点位")
    @RequestMapping(value = "/pointConvert")
    public FocRespone pointConvert() {

        QueryWrapper qw = new QueryWrapper();
        //mp_code不为空的
        qw.isNotNull("mp_code");
        List<FocPoint> list = focPointService.list(qw);
        for (FocPoint focPoint : list) {
            focPointService.toPointConver(focPoint);
        }
        return FocRespone.ok();
    }



    /**
     * 登录foc
     */
    @AutoLog(value = "foc操作-login")
    @ApiOperation(value = "foc操作-login", notes = "foc操作-login")
    @RequestMapping(value = "/login")
    public FocRespone login() {
        //组装请求体
        FocRequest focRequest = new FocRequest();
        LonginDTO longinDTO = new LonginDTO();
        String pwd = Md5Util.md5Encode("CInterface", "utf-8");
        longinDTO.setUsername("CInterface");
        longinDTO.setPassword(pwd);
        longinDTO.setIp("202.151.2.1");
        longinDTO.setLogin_time(System.currentTimeMillis());
        focRequest.setData(longinDTO);
        log.debug("登录请求路径以及参数：" + emsUrl + "/north/login" + " 请求参数：" + JSONObject.toJSONString(focRequest));
        String post = HttpUtil.post(emsUrl + "/north/login", JSONObject.toJSONString(focRequest));
        log.debug("登录返回信息：{}", post);
        JSONObject result = JSONObject.parseObject(post);
        String token = result.getJSONObject("data").getString("token");
        redisUtil.set("token", token);
        return FocRespone.ok();
    }



    /**
     * 设备名称问题
     */
    @AutoLog(value = "foc操作-手动刷新-设备名问题")
    @ApiOperation(value = "foc操作-手动刷新-设备名问题", notes = "foc操作-手动刷新-设备名问题")
    @RequestMapping(value = "/deviceConvert")
    // @PostConstruct
    @Transactional(rollbackFor = Exception.class)
    public FocRespone deviceConvert() {
        //获取存在下划线的空间
        LambdaQueryWrapper<FocDevice> spaceLambdaQueryWrapper = new QueryWrapper<FocDevice>().lambda();
        spaceLambdaQueryWrapper.like(FocDevice::getName, "^");

        List<FocDevice> list = focDeviceService.list(spaceLambdaQueryWrapper);
        //如果不为空则进行遍历
        if (CollectionUtil.isEmpty(list)) {
            FocRespone.ok();
        }

        for (FocDevice focDevice : list) {
            String[] split = focDevice.getName().split("^");
            focDevice.setName(split[0]);
            focDeviceService.updateById(focDevice);
        }
        return FocRespone.ok();
    }


  /*  *//**
     * 设备名称问题
     *//*
    @AutoLog(value = "foc操作-手动刷新-设备名问题")
    @ApiOperation(value = "foc操作-手动刷新-设备名问题", notes = "foc操作-手动刷新-设备名问题")
    @RequestMapping(value = "/pointConvert")
    // @PostConstruct
    @Transactional(rollbackFor = Exception.class)
    public FocRespone pointConvert() {
        //获取存在下划线的空间
        LambdaQueryWrapper<FocDevice> spaceLambdaQueryWrapper = new QueryWrapper<FocDevice>().lambda();
        spaceLambdaQueryWrapper.like(FocDevice::getName, "^");

        List<FocDevice> list = focDeviceService.list(spaceLambdaQueryWrapper);
        //如果不为空则进行遍历
        if (CollectionUtil.isEmpty(list)) {
            FocRespone.ok();
        }

        for (FocDevice focDevice : list) {
            String[] split = focDevice.getName().split("^");
            focDevice.setName(split[0]);
            focDeviceService.updateById(focDevice);
        }
        return FocRespone.ok();
    }*/


    /**
     * 登录foc
     */
    @AutoLog(value = "foc操作-手动刷新-下划线")
    @ApiOperation(value = "foc操作-手动刷新-下划线", notes = "foc操作-手动刷新-下划线")
    @RequestMapping(value = "/spaceConvertSide")
    //   @PostConstruct
    @Transactional(rollbackFor = Exception.class)
    public FocRespone spaceConvertSide() {
        //获取存在下划线的空间
        LambdaQueryWrapper<FocSpace> spaceLambdaQueryWrapper = new QueryWrapper<FocSpace>().lambda();
        spaceLambdaQueryWrapper.like(FocSpace::getName, "#");
        spaceLambdaQueryWrapper.eq(FocSpace::getSpaceType, "楼宇");
        List<FocSpace> list = focSpaceService.list(spaceLambdaQueryWrapper);
        //如果不为空则进行遍历
        if (CollectionUtil.isEmpty(list)) {
            FocRespone.ok();
        }
        //构建容器
        Map<String, List<FocSpace>> listMap = new HashMap<>();
        for (FocSpace focSpace : list) {
            //获取当前空间下的所有子空间
            LambdaQueryWrapper<FocSpace> focSpaceLambdaQueryWrapper = new QueryWrapper<FocSpace>().lambda();
            focSpaceLambdaQueryWrapper.eq(FocSpace::getParentGuid, focSpace.getGuid());
            //对名称进行分割
            String[] split = focSpace.getName().split("#");
            if (split == null) {
                continue;
            }
            if (split.length != 2) {
                continue;
            }
            if (split[1] == null) {
                continue;
            }
            List<FocSpace> focSpaces = listMap.get(split[0]);
            if (focSpaces == null) {
                focSpaces = new ArrayList<>();
                focSpaces.add(focSpace);
                listMap.put(split[0], focSpaces);
            } else {
                focSpaces.add(focSpace);
            }
        }
        //将得到的数据进行遍历
        if (CollectionUtil.isEmpty(listMap)) {
            return FocRespone.ok();
        }

        for (Map.Entry<String, List<FocSpace>> entry : listMap.entrySet()) {
            //创建新的空间
            String guid = System.currentTimeMillis() + "";
            FocSpace focSpace = new FocSpace();
            focSpace.setName(entry.getKey());
            focSpace.setGuid(guid);
            focSpace.setSpaceType("楼宇");
            focSpace.setParentGuid(entry.getValue().get(0).getParentGuid());
            focSpaceService.save(focSpace);
            for (FocSpace focSpace1 : entry.getValue()) {
                focSpace1.setParentGuid(guid);
                focSpace1.setName(focSpace1.getName().split("#")[1]);
                focSpaceService.updateById(focSpace1);
            }
        }
        return FocRespone.ok();
    }

    /**
     * 登出
     */
    @AutoLog(value = "foc操作-登出")
    @ApiOperation(value = "foc操作-登出", notes = "foc操作-登出")
    @RequestMapping(value = "/logout")
    public FocRespone logout() {
        FocRequest focRequest = new FocRequest();
        focRequest.setData(null);
        log.debug("登出请求路径以及参数：" + emsUrl + "/north/logout" + " 请求参数：" + JSONObject.toJSONString(focRequest, SerializerFeature.WriteMapNullValue) + "[token]" + redisUtil.get("token"));
        HttpResponse execute = HttpUtil.createPost(emsUrl + "/north/logout").header("token", redisUtil.get("token").toString()).body(JSONObject.toJSONString(focRequest)).execute();
        String body = execute.body();
        log.debug("登出返回信息：{}", body);
        return FocRespone.ok();
    }

    /**
     * foc设置ems推送策略
     */
    @AutoLog(value = "foc操作-foc设置ems推送策略")
    @ApiOperation(value = "foc操作-foc设置ems推送策略", notes = "foc操作-foc设置ems推送策略")
    @RequestMapping(value = "/online_data_strategy_add")
    public FocRespone setEmsPushPolicy() {
        //先查詢策略並全部刪除
        Object strategyObj = getStrategy().getData();
        if (strategyObj == null) {
            return FocRespone.ok();
        }
        JSONArray strategy = JSONArray.parseArray(JSONObject.toJSONString(strategyObj + ""));
        if (CollectionUtil.isNotEmpty(strategy)) {
            for (int i = 0; i < strategy.size(); i++) {
                JSONObject jsonObject = strategy.getJSONObject(i);
                String strategy_id = jsonObject.getString("strategy_id");
                deleteStrategy(strategy_id);
            }
        }
        JSONObject jsonObject = new JSONObject();
        QueryWrapper qw = new QueryWrapper();
        qw.isNull("strategy_id");
        FocStrategy focStrategy = focStrategyService.getOne(qw);
        //获取待添加策略
        FocRequest focRequest = new FocRequest();
        //策略名称
        jsonObject.put("name", focStrategy.getName());
        //空间节点数组
        jsonObject.put("space_guids", focStrategy.getSpaceGuids());
        //设备节点数组
        jsonObject.put("device_guids", focStrategy.getDeviceGuids());
        //周期类型
        jsonObject.put("mode", focStrategy.getMode());
        focRequest.setData(jsonObject);
        Object tokenObj = redisUtil.get("token");
        if (tokenObj == null) {
            login();
        }
        log.debug("ems推送策略请求路径以及参数：" + emsUrl + "/north/online_data_strategy_add" + " 请求参数：" + JSONObject.toJSONString(focRequest, SerializerFeature.WriteMapNullValue) + "[token]" + redisUtil.get("token"));
        String post = HttpUtil.createPost(emsUrl + "/north/online_data_strategy_add").header("token", redisUtil.get("token").toString()).body(JSONObject.toJSONString(focRequest)).execute().body();
        log.debug("ems推送策略返回信息：{}", post);
        JSONObject result = JSONObject.parseObject(post);
        result = result.getJSONObject("data");
        //策略id
        String strategyId = result.getString("strategy_id");
        focStrategy.setStrategyId(Integer.parseInt(strategyId));
        focStrategyService.updateById(focStrategy);

        return FocRespone.ok();

    }

    /**
     * 查詢策略
     */
    @AutoLog(value = "foc操作-查询策略")
    @ApiOperation(value = "foc操作-查询策略", notes = "foc操作-查询策略")
    @GetMapping(value = "/getStrategy")
    public FocRespone getStrategy() {
        JSONObject jsonObject = new JSONObject();
        FocRequest focRequest = new FocRequest();
        focRequest.setData(jsonObject);
        Object tokenObj = redisUtil.get("token");
        if (tokenObj == null) {
            login();
        }
        log.debug("ems推送策略请求路径以及参数：" + emsUrl + "/north/online_data_strategy_query" + " 请求参数：" + JSONObject.toJSONString(focRequest, SerializerFeature.WriteMapNullValue));
        String post = HttpUtil.createPost(emsUrl + "/north/online_data_strategy_query").header("token", redisUtil.get("token").toString()).body(JSONObject.toJSONString(focRequest)).execute().body();
        log.debug("ems推送策略返回信息：{}", post);
        JSONObject result = JSONObject.parseObject(post);
        result = result.getJSONObject("data");
        JSONArray strategies = result.getJSONArray("strategies");
        return FocRespone.ok(strategies);


    }

    /**
     * 删除策略
     */
    @AutoLog(value = "foc操作-删除策略")
    @ApiOperation(value = "foc操作-删除策略", notes = "foc操作-删除策略")
    @GetMapping(value = "/deleteStrategy")
    public FocRespone deleteStrategy(@RequestParam(name = "id", required = true) String id) {
        FocStrategy focStrategy = focStrategyService.getById(id);
        // focStrategyService.removeById(id);
        //删除策略
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("strategy_id", focStrategy.getStrategyId());
        FocRequest focRequest = new FocRequest();
        focRequest.setData(jsonObject);
        Object tokenObj = redisUtil.get("token");
        if (tokenObj == null) {
            login();
        }
        log.debug("ems推送策略请求路径以及参数：" + emsUrl + "/north/online_data_strategy_del" + " 请求参数：" + JSONObject.toJSONString(focRequest, SerializerFeature.WriteMapNullValue) + "[token]" + redisUtil.get("token"));
        String post = HttpUtil.createPost(emsUrl + "/north/online_data_strategy_del").header("token", redisUtil.get("token").toString()).body(JSONObject.toJSONString(focRequest)).execute().body();
        log.debug("ems推送策略返回信息：{}", post);
        //更新策略状态
        focStrategy.setDelFlag(1);
        focStrategyService.updateById(focStrategy);
        return FocRespone.ok();
    }


    /**
     * 策略
     */

    /**
     * 在线告警订阅
     */
    @AutoLog(value = "foc操作-在线告警订阅")
    @ApiOperation(value = "foc操作-在线告警订阅", notes = "foc操作-在线告警订阅")
    @RequestMapping(value = "/online_alarm_subscribe")
    public FocRespone onlineAlarmSubscribe() {
        Object tokenObj = redisUtil.get("token");
        if (tokenObj == null) {
            login();
        }
        FocRequest focRequest = new FocRequest();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("subscribe", true);
        focRequest.setData(jsonObject);
        log.info("ems在线告警订阅请求路径以及参数：" + emsUrl + "/north/online_alarm_subscribe" + " 请求参数：" + JSONObject.toJSONString(focRequest, SerializerFeature.WriteMapNullValue) + "[token]" + redisUtil.get("token"));

        String post = HttpUtil.createPost(emsUrl + "/north/online_alarm_subscribe").header("token", redisUtil.get("token").toString()).body(JSONObject.toJSONString(focRequest)).execute().body();
        log.info("ems在线告警订阅返回信息：{}", post);
        return FocRespone.ok();

    }

    /*
     *//**
     * 在线告警接收
     *//*
    @AutoLog(value = "foc操作-在线告警接收")
    @ApiOperation(value = "foc操作-在线告警接收", notes = "foc操作-在线告警接收")
    @PostMapping(value = "north/online_alarm_push")
    public void onlineAlarmPush(@RequestBody FocPushPorintDataDTO pushPorintDataDTO) {
        //解析推送过来的数据
        List<DevicePishDTO> devices = pushPorintDataDTO.getDevices();
        for (DevicePishDTO devicePishDTO : devices) {
            List<PontPustDTO> points = devicePishDTO.getPoints();
            for (PontPustDTO pontPustDTO : points) {
                //保存到数据库
                FocPointData focPointData = new FocPointData();
                focPointData.setPortGuid(pontPustDTO.getGuid());
                focPointData.setValue(pontPustDTO.getValue());
                focPointData.setTimestam(pontPustDTO.getTimestamp());
                focPointData.setStatus(devicePishDTO.getStatus());
                focPointData.setGuid(devicePishDTO.getGuid());
                focPointData.setStrategyId(pushPorintDataDTO.getStrategy_guid());
                focPointData.setPeriod(pushPorintDataDTO.getPeriod());
                focPointDataService.save(focPointData);
            }
        }


    }*/

    /**
     * 告警操作同步
     */
    @AutoLog(value = "foc操作-告警操作同步")
    @ApiOperation(value = "foc操作-告警操作同步", notes = "foc操作-告警操作同步")
    @PostMapping(value = "north/alarm_operation_sync")
    public void alarmOperationSync(@RequestBody List<Map> requestMap) {
        JSONObject jsonObject = new JSONObject();

    }


}
